<template>
  <el-dialog class="userLogin" :visible.sync="showForm" width="880px" top="0" :show-close="true" :modal-append-to-body="false">
    <div class="form-wrap">
      <div class="form">
        <img class="form-bg" src="@/assets/img/login-bg.png" alt="login" />
        <div class="form-list">
          <!-- <img class="user_logo" src="@/assets/img/logo.png" alt="logo" /> -->
          <el-input placeholder="请输入你的昵称" v-if="!isLogin" v-model="user.name">
          </el-input>
          <el-input placeholder="请输入联系邮箱或账号" v-model="user.email">
          </el-input>
          <!-- 注册默认邮箱验证 登录默认密码验证 -->
          <el-input v-if="isLogin && !isMail" show-password placeholder="请输入密码（长度6-22位之间）" v-model="user.password">
          </el-input>
          <el-input ref="mailInput" v-if="!isLogin || isMail" placeholder="请输入邮箱验证码" v-model="user.code">
            <el-button @click="sendMailCode(user.email)" :disabled="hasCode" slot="append" icon="el-icon-s-promotion">
              {{ hasCode ? '5分钟后可发送' : '获取验证码' }}</el-button>
          </el-input>
          <div class="user_tip">
            <el-link @click="isLogin = !isLogin">{{ isLogin ? '未有账号？点击注册！' : '已有账号？点击登录！' }}</el-link>
            <el-link type="success" v-if="isLogin" @click="isMail = !isMail">{{ isMail ? '密码' : '邮箱' }}登录</el-link>
          </div>
          <div>
            <el-button @click="submit" round type="info" class="user_btn">{{ isLogin ? '登录' : '注册' }}</el-button>
          </div>
          <el-button round class="user_btn" @click="goUrl($admin)">后台管理</el-button>
        </div>
      </div>
    </div>
  </el-dialog>
</template>
<script>

export default {
  name: 'LoginForm',
  data() {
    return {
      hasCode: false, // 等待验证码输入
      isMail: false, // 邮箱输入
      showForm: false, // 展示登陆注册框
      isLogin: false, // 登录
      // 用户信息
      user: {
        name: '',
        email: '',
        password: '',
        code: '',
      },
    }
  },
  created() {
    this.$bus.on('showLogin', this.showLogin)
    this.$bus.on('closeLogin', this.closeLogin)
  },
  methods: {
    goUrl(url) {
      window.open(url)
    },
    // 提交
    submit() {
      if (this.isLogin) {
        this.useLogin()
      } else {
        this.useRegister()
      }
    },
    // 注册
    useRegister() {
      // 注册 采用邮箱验证码
      if (this.hasCode) {
        // 校验邮箱
        this.verifyMail(this.user.email, this.user.code, () => {
          // 注册用户
          this.$api
            .httpRegister({
              email: this.user.email,
              name: this.user.name,
            })
            .then((res) => {
              if (res.code == 200) {
                this.$message.success('注册成功')
                this.$notify({
                  title: '您的账户为：' + this.user.email,
                  message: '初始密码为：123456',
                  type: 'success',
                  duration: 0,
                })
                // 保留用户登录信息
                this.saveUser(res.data.token, res.data.user)
              } else {
                this.$message.error(res.message)
              }
            })
        })
      } else {
        // 请点击获取邮箱验证码
        this.$message.warning('请点击获取邮箱验证码')
      }
    },
    // 登录
    useLogin() {
      // 登录 可密码 和 邮箱两种方式
      // 1、邮箱
      if (this.isMail) {
        // 未获取邮箱验证码邮箱
        if (this.hasCode) {
          // 校验邮箱
          this.verifyMail(this.user.email, this.user.code, () => {
            this.$api
              .httpUserLoginInfo({ email: this.user.email })
              .then((res) => {
                if (res.code == 200) {
                  this.$message.success('欢迎回来！')
                  // 保留用户登录信息
                  this.saveUser(res.data.token, res.data.user)
                  // 强刷新
                  // this.$router.go(0)
                }
              })
          })
        } else {
          // 请点击获取邮箱验证码
          this.$message.warning('请点击获取邮箱验证码')
        }
      } else {
        // 密码登录
        let data = {
          email: this.user.email,
          password: this.user.password,
        }
        this.$api.httpLogin(data).then((res) => {
          if (res.code == 200) {
            // 邮箱登录成功 保存用户信息
            this.$message.success(res.message)
            // 保留用户登录信息
            this.saveUser(res.data.token, res.data.user)

          } else {
            // 登录失败
            this.$message.warning(res.message)
          }
        })
      }
    },
    // 保存用户信息
    saveUser(token, user) {
      this.showForm = false // 隐藏
      // 存储token
      this.$storage.setSession('token', token)
      this.$store.commit('login', {
        userId: user.userId || user.id,
        name: user.name,
        email: user.email,
        admin: user.admin,
      })
      this.$bus.emit('isLogin')
      this.isLogin = true
    },
    // 关闭
    closeLogin() {
      this.showForm = false
    },
    // 跳出登录框
    showLogin(user = {}) {
      this.showForm = true
      this.user = user
    },
    // 发送邮箱验证码
    sendMailCode(email) {
      // 邮箱正则
      const reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/
      if (!reg.test(email)) {
        this.$message.warning('请输入正确的邮箱格式；温馨提示：账号只能使用密码登录')
        return false
      } 

      this.$api.httpMailCode({ email }).then((res) => {
        if (res.code == 200) {
          this.$message.success('邮箱验证码已发送')
          this.$refs['mailInput'].focus()
          this.hasCode = true
          // 5分钟后可继续发送验证码
          setTimeout(() => {
            this.hasCode = false
          }, 5 * 60000)
        }
      })
    },
    // 验证邮箱
    verifyMail(email, code, cb) {
      this.$api.httpMailVerify({ email, code }).then((res) => {
        if (res.code == 200) {
          // 邮箱登录成功 保存用户信息
          cb()
        } else {
          // 验证码错误，请重新输入
          this.$message.warning('验证码错误，请重新输入')
        }
      })
    },
  },
}
</script>
<style scoped lang="scss">
$login_width: 320px;

::v-deep .el-input {
  width: $login_width;
  margin-bottom: 18px;
}

.user_btn {
  width: 300px;
  height: 50px;
  margin-top: 24px;
}

.user_logo {
  margin: 60px 0 40px;
  width: 340px;
  display: block;
  opacity: 0.7;
  border-radius: 4px;
}

.user_tip {
  text-align: right;
  width: $login_width;
}

.form {
  display: flex;
}

.form-bg {
  width: 500px;
  font-size: 0;
  display: block;
}

.form-list {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  box-sizing: border-box;
  padding-top: 80px;
}

::v-deep .el-dialog__header {
  padding: 0;
}

::v-deep .el-dialog__body {
  padding: 0;
}

::v-deep .el-dialog {
  margin: 0;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

@media screen and (max-width: 1200px) {
  ::v-deep .el-dialog {
    width: 96% !important;
  }

  ::v-deep .el-dialog__body {
    padding-bottom: 24px;
  }

  .form-bg {
    display: none;
  }
}
</style>
